package com.smt.modules.app.controller;

import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.smt.common.enums.Code;
import com.smt.common.enums.StageEnum;
import com.smt.common.utils.Constant;
import com.smt.common.utils.EnumToKeyUtil;
import com.smt.modules.app.annotation.BillAndGrade;
import com.smt.modules.app.annotation.Login;
import com.smt.modules.app.annotation.LoginUser;
import com.smt.modules.bus.entity.MemberUserEntity;
import com.smt.modules.bus.entity.ProjectTaskEntity;
import com.smt.modules.bus.service.MemberUserService;
import com.smt.modules.bus.service.ProjectTaskService;
import com.smt.modules.bus.vo.ProjectTaskVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import com.smt.common.base.BaseController;
import com.smt.modules.bus.vo.ProjectVo;
import com.smt.modules.bus.entity.ProjectEntity;
import com.smt.modules.bus.service.ProjectService;
import com.smt.common.utils.PageUtils;
import com.smt.common.utils.R;

import javax.validation.constraints.NotNull;


/**
 * 项目信息表
 *
 * @author murong
 * @email 981620741@qq.com
 * @date 2018-09-29 15:37:09
 */
@RestController
@RequestMapping("app/project")
@Api(tags = {"AppProjectController"}, description = "项目信息表(客户端接口)")
public class AppProjectController extends BaseController {

    @Autowired
    @Qualifier("projectService")
    private ProjectService projectService;

    @Autowired
    private ProjectTaskService projectTaskService;

    @Autowired
    private MemberUserService memberUserService;

    /**
     * 查询项目信息表分页方法
     *
     * @param params
     * @return
     */
    @PostMapping("/list")
    @ApiOperation(value = "/list", notes = "根据条件查询", response = ProjectVo.class)
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = projectService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "根据表ID查询", response = ProjectVo.class)
    public R info(@PathVariable("id") Long id) {
        ProjectEntity project = projectService.selectById(id);

        return R.ok().put("project", project);
    }

    /**
     * 保存
     */
    @Login
    @PostMapping("/add")
    @ApiOperation(value = "新建项目（预置模板）", notes = "创建一个新的项目")
    @BillAndGrade(value = Constant.TASK_4)
    public R save(@RequestBody ProjectVo project, @LoginUser MemberUserEntity memberUserEntity) {
        return projectService.save(project, memberUserEntity);
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    @ApiOperation(value = "更新信息保存", response = ProjectVo.class, httpMethod = "PUT")
    public R update(@RequestBody ProjectEntity project) {
        projectService.updateById(project.copyPropertiesTo(new ProjectEntity()));

        return R.ok();
    }

    /**
     * 获取项目列表
     */
    @Login
    @GetMapping("/projectLists")
    @ApiOperation(value = "获取项目列表（展示成员）", response = ProjectVo.class, httpMethod = "GET")
    public R projectLists(@LoginUser MemberUserEntity memberUserEntity) {
        return projectService.projectLists(memberUserEntity);
    }

    /**
     * 项目修改+删除
     */
    @Login
    @PostMapping("/projectEdit")
    @ApiOperation(value = "项目简介修改+项目删除（成员不能，创建者才能）获取当前成员的所有参见项目", response = ProjectVo.class)
    public R projectEdit(@RequestBody ProjectVo projectVo,  @LoginUser MemberUserEntity entity) {
        return projectService.projectEdit(projectVo, entity);
    }

    /**
     * 当前项目修改+删除
     */
    @Login
    @PutMapping("/currentProjectEdit")
    @ApiOperation(value = "当前项目修改+删除", httpMethod = "PUT")
    public R currentProjectEdit(@RequestBody ProjectVo projectVo, @LoginUser MemberUserEntity entity) {
        return projectService.currentProjectEdit(projectVo, entity);
    }

    /**
     * 项目界面整体展示
     *
     * @param projectId
     */
    @GetMapping("/projectManage/{projectId}")
    @ApiOperation(value = "项目界面整体展示(任务默认展示【概念阶段的任务，但是不展示子任务】)", httpMethod = "GET")
    public R projectManageShow(@PathVariable(value = "projectId") Long projectId) {
        return projectService.projectManageShow(projectId);
    }


    /**
     * 修改阶段任务的负责人名
     *
     * @param projectTaskVo
     * @param userId
     */
    @Login
    @PostMapping("/editStageName")
    @ApiOperation(value = "修改阶段任务的负责人名", httpMethod = "POST")
    public R editStageName(@RequestBody ProjectTaskVo projectTaskVo, @RequestAttribute("userId") long userId) {
        Boolean b = projectService.editStageName(projectTaskVo, userId);
        if (b) {
            return R.ok("您修改成功！");
        } else {
            return R.error(EnumToKeyUtil.toInt(Code.MISSING_PERMISSION),"您无修改此数据的权限");
        }
    }

    /**
     * 通过项目id获取项目内容
     *
     * @param projectId
     */
    @PostMapping("/getProjectById/{projectId}")
    @ApiOperation(value = "通过项目id获取项目内容", httpMethod = "POST")
    public R getProjectById(@PathVariable(value = "projectId") Long projectId) {

        return projectService.getProjectById(projectId);
    }

    /**
     * 获取该用户下所有的项目名字
     */
    @Login
    @PostMapping("/getProjectNameList")
    @ApiOperation(value = "获取该用户下所有的项目名字", httpMethod = "POST")
    public R getProjectNameList(@LoginUser MemberUserEntity memberUserEntity) {

        return projectService.getProjectNameList(memberUserEntity);
    }

    /**
     * 任务修改权限校验 (修改任务信息)
     *
     * @param projectTaskVo
     */
    @Login
    @PutMapping("/projectPermissionEdit")
    @ApiOperation(value = "任务信息修改权限校验（更换责任人，删除修改驳回等等） (修改任务信息)", httpMethod = "PUT")
    @BillAndGrade(value = Constant.TASK_1)
    public R projectTaskEdit(@RequestBody ProjectTaskVo projectTaskVo,
                             @LoginUser MemberUserEntity memberUserEntity) {
        return projectService.projectTaskEdit(projectTaskVo, memberUserEntity);
    }

    /**
     * 获取当前用户属于什么阶段，可以有哪些操作权限
     *
     * @param projectId
     * @param stageId
     */
    @Login
    @GetMapping("/getStageUser/{projectId}/{stageId}")
    @ApiOperation(value = "获取当前用户属于什么阶段，可以有哪些操作权限", httpMethod = "GET")
    public R getStageUser(@PathVariable(value = "projectId") Long projectId,
                          @PathVariable(value = "stageId") Integer stageId,
                          @LoginUser MemberUserEntity memberUserEntity) {
        return projectService.projectStageUser(projectId, stageId, memberUserEntity);
    }

    /**
     * 获取当前项目下的阶段的任务集合
     *
     * @param projectId
     * @param stageId
     */
    @Login
    @GetMapping("/list/{projectId}/{stageId}")
    @ApiOperation(value = "获取项目下的各个阶段的任务集合", httpMethod = "GET")
    @BillAndGrade(value = Constant.TASK_2)
    public R getSubTask(@PathVariable(value = "projectId") Long projectId,
                        @PathVariable(value = "stageId") Integer stageId,
                        @LoginUser MemberUserEntity memberUserEntity) {
        return projectService.getTaskList(projectId, stageId);
    }

    /**
     * 获取当前用户属于什么阶段，可以有哪些操作权限
     *
     * @deprecated 并入内部方法中
     */
    @GetMapping("/getUserPermission")
    @ApiOperation(value = "获取当前用户属于什么阶段，可以有哪些操作权限（不用）", httpMethod = "GET", hidden = true)
    public R getUserPermission(/*参数待定*/) {
        return R.ok();
    }

    /**
     * 获取当前项目所有阶段责任人集合
     *
     * @param projectId
     */
    @GetMapping("/responsible/{projectId}")
    @ApiOperation(value = "获取当前项目所有阶段责任人集合", httpMethod = "GET")
    public R getSubTask(@PathVariable(value = "projectId") @NotNull(message = "项目id不能为空！") Long projectId) {
        List<ProjectTaskEntity> projectTaskList = projectTaskService.selectList(new EntityWrapper<ProjectTaskEntity>()
                .eq("project_id", projectId)
                .eq("status", "400"));
        Map<Integer, Long> stageMap = new HashMap<>();
        Collections.sort(projectTaskList, (x, y) -> {
            return x.getStageId().compareTo(y.getStageId());
        });
        projectTaskList.stream()
                .forEach(p -> {
                    if (p.getMemberExist() == 0) {
                        stageMap.put(p.getStageId(), p.getStageMemberId());
                    } else {
                        stageMap.put(p.getStageId(), null);
                    }
                });
        Long[] names = new Long[stageMap.size()];
        int i = 0;
        Set<Map.Entry<Integer, Long>> entries = stageMap.entrySet();
        Iterator<Map.Entry<Integer, Long>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<Integer, Long> next = iterator.next();
            //获取的任务的负责人id查找他的无效位,在于阶段负责人中比较,如果发现是无效位则将状态=null
            boolean flag = false;
            List<ProjectTaskEntity> projectTask = projectTaskService.selectList(new EntityWrapper<ProjectTaskEntity>()
                    .eq("member_id", next.getValue()));
            if(projectTask.size() != 0) {
                if (projectTask.get(0).getMemberExist() == 1) {
                    flag = true;
                }
            }
            if (flag) {
                names[i++] = null;
            } else {
                names[i++] = next.getValue();
            }

        }
        return R.ok().put("stageIds", names);
    }
}
